import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit'
import { Connection, CreateConnectionData, UpdateConnectionData } from '@/types/connection'
import * as connectionAPI from '@/services/connectionAPI'

interface ConnectionState {
  connections: Connection[]
  currentConnection: Connection | null
  loading: boolean
  error: string | null
  testingConnection: boolean
  testResult: {
    success: boolean
    message: string
  } | null
}

const initialState: ConnectionState = {
  connections: [],
  currentConnection: null,
  loading: false,
  error: null,
  testingConnection: false,
  testResult: null,
}

// 异步thunks
export const fetchConnections = createAsyncThunk(
  'connection/fetchConnections',
  async () => {
    const response = await connectionAPI.getConnections()
    return response.data
  }
)

export const createConnection = createAsyncThunk(
  'connection/createConnection',
  async (connectionData: CreateConnectionData) => {
    const response = await connectionAPI.createConnection(connectionData)
    return response.data
  }
)

export const updateConnection = createAsyncThunk(
  'connection/updateConnection',
  async ({ id, data }: { id: string; data: UpdateConnectionData }) => {
    const response = await connectionAPI.updateConnection(id, data)
    return response.data
  }
)

export const deleteConnection = createAsyncThunk(
  'connection/deleteConnection',
  async (id: string) => {
    await connectionAPI.deleteConnection(id)
    return id
  }
)

export const testConnection = createAsyncThunk(
  'connection/testConnection',
  async (id: string) => {
    const response = await connectionAPI.testConnection(id)
    return response.data
  }
)

const connectionSlice = createSlice({
  name: 'connection',
  initialState,
  reducers: {
    setCurrentConnection: (state, action: PayloadAction<Connection | null>) => {
      state.currentConnection = action.payload
    },
    clearTestResult: (state) => {
      state.testResult = null
    },
    clearError: (state) => {
      state.error = null
    },
  },
  extraReducers: (builder) => {
    builder
      // fetchConnections
      .addCase(fetchConnections.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(fetchConnections.fulfilled, (state, action) => {
        state.loading = false
        state.connections = action.payload.connections || []
      })
      .addCase(fetchConnections.rejected, (state, action) => {
        state.loading = false
        state.error = action.error.message || '获取连接列表失败'
      })
      // createConnection
      .addCase(createConnection.fulfilled, (state, action) => {
        state.connections.unshift(action.payload)
      })
      // updateConnection
      .addCase(updateConnection.fulfilled, (state, action) => {
        const index = state.connections.findIndex(c => c.id === action.payload.id)
        if (index !== -1) {
          state.connections[index] = action.payload
        }
        if (state.currentConnection?.id === action.payload.id) {
          state.currentConnection = action.payload
        }
      })
      // deleteConnection
      .addCase(deleteConnection.fulfilled, (state, action) => {
        state.connections = state.connections.filter(c => c.id !== action.payload)
        if (state.currentConnection?.id === action.payload) {
          state.currentConnection = null
        }
      })
      // testConnection
      .addCase(testConnection.pending, (state) => {
        state.testingConnection = true
        state.testResult = null
      })
      .addCase(testConnection.fulfilled, (state, action) => {
        state.testingConnection = false
        state.testResult = {
          success: true,
          message: action.payload.message || '连接测试成功'
        }
      })
      .addCase(testConnection.rejected, (state, action) => {
        state.testingConnection = false
        state.testResult = {
          success: false,
          message: action.error.message || '连接测试失败'
        }
      })
  },
})

export const {
  setCurrentConnection,
  clearTestResult,
  clearError,
} = connectionSlice.actions

export default connectionSlice.reducer